package com.sky.baidu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClassName: BaiDuUtil
 * Package: com.sky.baidu
 * Description:
 *
 * @Author 八云
 * @Create 2025/3/25 22:12
 * @Version 1.0
 */

@Component
public class BaiDuUtil {

    @Autowired
    private BaiDuGeocoding baiDuGeocoding;

    @Autowired
    private BaiDuDirve baiDuDirve;

    /**
     * 调用官方代码，解析返回 string格式的经纬度
     * @param responseStr
     * @return
     * @throws Exception
     */
    public String parseLocation(String responseStr) throws Exception {
        // 官方代码返回结果的格式为: showLocation&&showLocation({"status":0,"result":{...}})
        String search = baiDuGeocoding.geocoding(responseStr);

        // 正则匹配出json字符串
        int startIndex = search.indexOf("{");
        int endIndex = search.lastIndexOf("}");
        String jsonContent = search.substring(startIndex, endIndex + 1);

        // json字符串转为json对象
        JSONObject json = JSON.parseObject(jsonContent);

        if (json.getInteger("status") != 0) {
            throw new RuntimeException("百度地图接口调用失败");
        }

        // 获取经纬度
        JSONObject location = json.getJSONObject("result").getJSONObject("location");
        // 转成字符串
        String lng = location.getString("lng");
        String lat = location.getString("lat");
        // 返回字符串数组 lng：[0] lat：[1]
        return lat+","+lng;
    }

    /**
     * 调用官方代码，解析返回 string格式的距离
     * @param origin
     * @param destination
     * @return
     * @throws Exception
     */
    public Integer parseDistance(String origin, String destination) throws Exception {
        // 官方代码返回结果的格式为: showLocation&&showLocation({"status":0,"result":{...}})
        String search = baiDuDirve.dirve(origin,destination);

        // 正则匹配出json字符串
        int startIndex = search.indexOf("{");
        int endIndex = search.lastIndexOf("}");
        String jsonContent = search.substring(startIndex, endIndex + 1);

        // json字符串转为json对象
        JSONObject json = JSON.parseObject(jsonContent);

        if (json.getInteger("status") != 0) {
            throw new RuntimeException("百度地图接口调用失败");
        }

        // 获取地点之间的距离
        Integer distance = json.getJSONObject("result").getJSONArray("routes").getJSONObject(0).getInteger("distance");
        return distance;
    }
}
